package com.example.jwt.framework.security.core;

import com.example.jwt.common.exception.user.UserPasswordNotMatchException;
import com.example.jwt.common.util.SecurityUtils;
import com.example.jwt.framework.security.context.AuthenticationContextHolder;
import com.example.jwt.project.sys.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @className: PasswordService
 * @description: 密码校验处理类
 * @author: LiJunYi
 * @create: 2023/4/27 9:03
 */
@Component
public class PasswordService {

    /**
     * 验证
     *
     * @param user 用户
     */
    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        if (!matches(user, password))
        {
            throw new UserPasswordNotMatchException();
        }
    }

    /**
     * 匹配
     *
     * @param user        用户
     * @param rawPassword 生密码
     * @return boolean
     */
    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }
}
